<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2019-12-13
 * Time: 17:58
 */

namespace app\api\service;

use app\api\model\StoreUser;
use app\api\model\TeamUser;
use app\api\model\User;
use app\api\model\UserInvitation;
use app\lib\exception\WeChatException;


require '/www/wwwroot/digcusmark.com/shuzi-cms/extend/crypt/wxBizDataCrypt.php';

class UserPhone extends Token
{

    protected $appid;

    protected $sessionKey;

    protected $encryptedData;

    protected $iv;


    public function get($post)
    {
        $encryptedData = $post['encrypted_data'];
        $iv = $post['iv'];
        $wxAppId = config('wx.app_id');
        $sessionKey = self::getCurrentTokenVar('session_key');
        $uid = self::getCurrentUid();
        $crypy = new \WXBizDataCrypt($wxAppId, $sessionKey);
        $errCode = $crypy->decryptData($encryptedData, $iv, $data );
        if($errCode == 0)
        {
            $data = json_decode($data,true);
            User::where('id','=',$uid)->update(['phone'=>$data['phoneNumber'],'status'=>3,'phone_time'=>time()]);
            $userInvitation = UserInvitation::where('invitee',$uid)->find();
            if($userInvitation) {
                if($userInvitation['type'] == 2) {
                    $storeUser = StoreUser::where('id',$userInvitation['inviter'])->find();
                    User::where('id',$uid)->update([
                        'store_id' => $storeUser['store_id']
                    ]);
                } elseif($userInvitation['type'] == 3){
                    $teamUser = TeamUser::where('id',$userInvitation['inviter'])->find();
                    User::where('id',$uid)->update([
                        'team_id' => $teamUser['team_id']
                    ]);
                }
            }
            return $data['phoneNumber'];
        }
        else{
            throw new WeChatException([
                'msg' => '获取手机号失败,请重试！',
                'errorCode' => $errCode
            ]);
        }
    }
}